var mongoose = require('mongoose');
const DataModel = require("../models/user_model");


exports.create = function(req, res, next){
    const dataModel = new DataModel(req.body);
    // console.log(user)
    dataModel.save()
        .then(data=>{
            res.json(data);
        })
}

exports.get = function(req, res, next){
    var id = req.params.id;
    DataModel.findById(id, function (err, data) {
        res.json(data);
    })
}

exports.update = function(req, res, next){
    var id = req.params.id;
    DataModel.findByIdAndUpdate(id, {$set: req.body}, {new:false})
        .then(data=>{
            //此时的返回值是修改之前的，而非修改之后的，所以可以去MongoDB中去查看修改以后的情况
            res.json(data);
        })
}
exports.remove = function(req, res, next){
    var id = req.params.id;
    DataModel.findByIdAndRemove(id, function(err,data){
        res.json(data);
    })
}

exports.list = function(req, res, next){
    var page = (req.body.page)?req.body.page:1;
    var rows = (req.body.rows)?req.body.rows:10;

    var queryCondition = {};
    if(req.body.name && (req.body.name.trim().length)>0){
        name = req.body.name;
        queryCondition = {
            "name":new RegExp(name,"i")
        }
    }

    DataModel.paginate(queryCondition,{page:parseInt(page),limit:parseInt(rows),sort:{_id:-1}},function(err, result){
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
}
exports.deletes = function(req, res, next){
    // console.log(req.body.ids);
    var ids = req.body.ids;
    // console.log(ids);
    if(ids.length>0){
        // console.log("123");
        // console.log(ids.length);
        DataModel.remove({_id:{$in:ids.split(",")}})
            .then(data=>{
                res.json({"msg":'success',"status":200})
            })
    }else{
        // console.log("404");
        res.json({"msg":'success',"status":404})
    }

}